home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / snip0493.zip / PFOPEN.C < prev    next >
C/C++ Source or Header  |  1993-04-05  |  2KB  |  79 lines

  1. /*
  2.  *  Written and released to the public domain by David Engel.
  3.  *
  4.  *  This function attempts to open a file which may be in any of
  5.  *  several directories.  It is particularly useful for opening
  6.  *  configuration files.  For example, PROG.EXE can easily open
  7.  *  PROG.CFG (which is kept in the same directory) by executing:
  8.  *
  9.  *      cfg_file = pfopen("PROG.CFG", "r", getenv("PATH"));
  10.  *
  11.  *  NULL is returned if the file can't be opened.
  12.  */
  13.  
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17.  
  18. #ifdef unix
  19.  #define SEP_CHARS ":"
  20. #else
  21.  #define SEP_CHARS ";"
  22. #endif
  23.  
  24. FILE *pfopen(const char *name, const char *mode, const char *dirs)
  25. {
  26.     char *ptr;
  27.     char *tdirs;
  28.     FILE *file = NULL;
  29.  
  30.     if (dirs == NULL || dirs[0] == '\0')
  31.         return NULL;
  32.  
  33.     if ((tdirs = malloc(strlen(dirs)+1)) == NULL)
  34.         return NULL;
  35.  
  36.     strcpy(tdirs, dirs);
  37.  
  38.     for (ptr = strtok(tdirs, SEP_CHARS); file == NULL && ptr != NULL;
  39.         ptr = strtok(NULL, SEP_CHARS))
  40.     {
  41.         size_t len;
  42.         char work[FILENAME_MAX];
  43.  
  44.         strcpy(work, ptr);
  45.         len = strlen(work);
  46.         if (len && work[len-1] != '/' && work[len-1] != '\\')
  47.             strcat(work, "/");
  48.         strcat(work, name);
  49.  
  50.         file = fopen(work, mode);
  51.     }
  52.  
  53.     free(tdirs);
  54.  
  55.     return file;
  56. }
  57.  
  58. #ifdef TEST
  59.  
  60. int main(int argc, char **argv)
  61. {
  62.     FILE *file;
  63.  
  64.     if (argc != 4)
  65.     {
  66.         fprintf(stderr, "usage: pfopen name mode dirs\n");
  67.         exit(1);
  68.     }
  69.  
  70.     file = pfopen(argv[1], argv[2], argv[3]);
  71.  
  72.     printf("%s \"%s\" with mode \"%s\"\n", (file == NULL) ?
  73.         "Could not open" : "Opened", argv[1], argv[2]);
  74.  
  75.     return 0;
  76. }
  77.  
  78. #endif
  79.